package com.threadpool;

import java.util.LinkedList;
import java.util.List;

/**
 * Created by houjinxin on 16/9/3.
 */
public class BlockQueue {

    private List queue = new LinkedList();

    private int limit = 10;

    public BlockQueue(int limit) {

        this.limit = limit;

    }

    public synchronized void enqueue(Object item)

            throws InterruptedException {

        while (this.queue.size() == this.limit) {

            wait();

        }

        if (this.queue.size() == 0) {

            notifyAll();

        }

        this.queue.add(item);

    }

    public synchronized Object dequeue()

            throws InterruptedException {

        while (this.queue.size() == 0) {

            wait();

        }

        if (this.queue.size() == this.limit) {

            notifyAll();

        }

        return this.queue.remove(0);

    }

    public static void main(String[] args) throws InterruptedException {
        BlockQueue blockQueue = new BlockQueue(20);

        for (int i = 0; i < 20; i++) {
            System.out.println(blockQueue.queue.size());
            blockQueue.enqueue(new Object());
        }
        for (int i = 0; i < 20; i++) {
            System.out.println(blockQueue.queue.size());
            blockQueue.dequeue();
        }

    }

}
